package com.qczl.weather.task;

import java.util.List;
import java.util.ResourceBundle;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qczl.core.util.DateUtil;
import com.qczl.core.util.HttpUtil;
import com.qczl.weather.dao.CityMapper;
import com.qczl.weather.dao.InfoMapper;
import com.qczl.weather.pojo.City;
import com.qczl.weather.pojo.Info;

@Component
@Service
public class WeatherTask {
	
	@Resource
	CityMapper cDao;
	
	@Resource
	InfoMapper iDao;
	
	
	ResourceBundle r = ResourceBundle.getBundle("config");
	
	/**
	 * 定时获取天气信息
	 */
	@Scheduled(cron = "0/1 0 0,6,12,18 * * ?")
//	@Scheduled(cron = "* * * * * ?")
	public void weather() {
		List<City> cList = cDao.selectAll();
		for (City c : cList) {
			String cName=c.getCityName();
			if(!c.getCityCode().equals("")||c.getCityCode()!=null){
				cName=c.getCityCode();
			}
			String s =  HttpUtil.sendPostRequest(r.getString("weather.url"), "city="+cName+"&key="+r.getString("weather.key"), false);
			Info inf = save(s);
			inf.setWeaId(new Long(c.getCityId()));
			iDao.insertSelective(inf);
		}
	}
	
	public Info save(String s){
		JSONObject obj = JSONObject.parseObject(s);
		JSONArray jArr = JSONArray.parseArray(obj.getString("HeWeather5"));
		JSONObject jo = (JSONObject)jArr.get(0); 
		Info i = new Info();
		i.setInfoBasic(jo.getString("basic"));
		i.setInfoForecast(jo.getString("daily_forecast"));
		if(jo.get("status").equals("ok")){
			i.setInfoStatus(0);
		}else{
			i.setInfoStatus(1);
		}
		JSONObject basic = JSONObject.parseObject(jo.getString("basic"));
		JSONObject update = JSONObject.parseObject(basic.getString("update"));
		String date = update.getString("loc")+":00";
		System.out.println("date"+DateUtil.convert2Date(date.toString()));
		i.setCreattime(DateUtil.convert2Date(date.toString()));
		return i;
	}
	
}
